package com.zhugang.week13.sort;

/**
 * @program algorithms
 * @description: InsertionSort
 * @author: chanzhugang
 * @create: 2022/10/17 23:31
 */
public class InsertionSort {

    /**
     * 插入排序
     *
     * @param arr
     * @param n
     */
    public void insertSort(int[] arr, int n) {
        // 每次从未排序区间把值插入到已排序区间正确的位置
        for (int i = 1; i < n; i++) {
            int val = arr[i];
            int j = i - 1;

           /* for (; j >= 0; j--) {
                if (arr[j] > val) {
                    arr[j + 1] = arr[j];
                } else {
                    break;
                }
            }*/
            while (j >= 0 && arr[j] > val) {
                arr[j + 1] = arr[j];
                j--;
            }
            // 值插入到正确的下标
            arr[j + 1] = val;
        }
    }

    public static void main(String[] args) {
        InsertionSort insertionSort = new InsertionSort();
        int[] arr = new int[]{5, 3, 1, 4, 2};
        insertionSort.insertSort(arr, arr.length);
        for (int i : arr) {
            System.out.println(i);
        }
    }
}